package com.aidex.web.controller.biz;

import com.aidex.biz.domain.*;
import com.aidex.biz.service.*;
import com.aidex.biz.utils.QrCodeUtils;
import com.aidex.common.annotation.Log;
import com.aidex.common.constant.Constants;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.AjaxResult;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.web.service.SysLoginService;
import com.aidex.framework.web.service.TokenService;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.ISysUserService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.util.*;
import java.util.regex.Pattern;


/**
 * 客户端基础接口
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-10-08
 */
@RestController("ApiClintManageController")
@RequestMapping("/biz/clint")
@Api(tags = "客户端基础接口")
public class ClintManageController extends BaseController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private EquInfoService equInfoService;

    @Autowired
    private RubbishTypeService rubbishTypeService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailsService orderDetailsService;


    @Autowired
    private AccountTypeService accountTypeService;
    @Autowired
    private WeChatLoginService weChatLoginService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SmSSendService smSSendService;


    /**
     * 分拣员-登录
     *
     * @return 结果
     */
    @ApiOperation(value = "客户端用户登录")
    @GetMapping("/clintLogin")
    @ApiImplicitParams({@ApiImplicitParam(name = "password", value = "登录密码", required = true),
            @ApiImplicitParam(name = "username", value = "登录名", required = true)})
    public R clintLogin(@RequestParam String username, String password) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, loginService.login(username, password));
        ajax.put("user", tokenService.getLoginUser(ajax.get(Constants.TOKEN).toString()));
        return R.data(ajax);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "获取客户端用户信息")
    @GetMapping("/getInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "token", required = true)})
    public R getInfo(String token) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", tokenService.getLoginUser(token));
        return R.data(ajax);
    }

    /**
     * 重置密码
     */
    @ApiOperation(value = "重置密码")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @GetMapping("/updatePwd")
    @ApiImplicitParams({@ApiImplicitParam(name = "oldPassword", value = "旧密码", required = true),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true)})
    public AjaxResult updatePwd(@RequestParam String oldPassword, String newPassword) {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 获取包裹信息 扫码
     *
     * @return 结果
     */
    @ApiOperation(value = "分拣时根据码CODE获取用户信息和设备信息")
    @GetMapping("/getPackageInfoByCode")
    @ApiImplicitParams({@ApiImplicitParam(name = "code", value = "加密串", required = true)})
    public R getPackageInfoByCode(@RequestParam String code) throws Exception {
        Map<String, Object> ajax = new HashMap<>();
        if (StringUtils.isNull(code) || StringUtils.isEmpty(code)) {
            return R.fail("码不能为空");
        }
        boolean isReCode = false;// code 是否重复
        // 查询当天是否有相同的包裹 重复入库开关
        Order order = new Order();

        order.setCreateTime(new Date());
        List<Order> orders = orderService.findList(order);
        if (null != orders && orders.size() > 0) {
            // 表示
            isReCode = true;
        }
        // 先验证手机号码
        if (this.isValidPhoneNumber(code)) {
            UserInfo userInfo = userInfoService.findOneByPhone(code,
                    SecurityUtils.getLoginUser().getUser().getCompanyId());
            EquInfo equInfo = null;
            equInfo = new EquInfo();
            equInfo.setEquXinghao("手机号码投递订单");
            if (null == userInfo) {
                userInfo = new UserInfo();
                userInfo.setType("0");
                userInfo.setPhone(code);
                userInfo.setNikeName("未注册用户");
                userInfo.setName("未注册用户");
                userInfo.setId(StringUtils.Getnum());
                userInfo.setUserInfoId(userInfo.getId());
                userInfo.setStatus("0");
                userInfo.setIsNewRecord();
                userInfo.setIsShiming(0);
                userInfo.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                weChatLoginService.register(userInfo);
            }
            ajax.put("recurCode", isReCode);
            ajax.put("userInfo", userInfo);
            ajax.put("equInfo", equInfo);
            return R.data(ajax);
        }

        String[] codeParam = code.split("&");
//        if (codeParam.length != 3) {
//            return R.fail("二维码格式不正确");
//        }
        // 如果是手机号码 先注册用户
        if (this.isValidPhoneNumber(codeParam[0])) {
            UserInfo userInfo = userInfoService.findOneByPhone(codeParam[0],
                    SecurityUtils.getLoginUser().getUser().getCompanyId());
            if (null == userInfo) {
                userInfo = new UserInfo();
                userInfo.setType("0");
                userInfo.setPhone(codeParam[0]);
                userInfo.setNikeName("未注册用户");
                userInfo.setName("未注册用户");
                userInfo.setId(StringUtils.Getnum());
                userInfo.setUserInfoId(userInfo.getId());
                userInfo.setStatus("0");
                userInfo.setIsNewRecord();
                userInfo.setIsShiming(0);
                userInfo.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                weChatLoginService.register(userInfo);
                code = userInfo.getId();
            } else {
                code = userInfo.getId();
            }
        } else {
            if ("LLB".equals(codeParam[0].substring(0, 3))) {
                code = codeParam[0].substring(3);
                code = QrCodeUtils.decrypt(code);
            } else {
                return R.fail("二维码格式不正确");
            }

        }
        try {
            UserInfo userInfo = userInfoService.get(code);
            EquInfo equInfo = null;
            if (userInfo.getCompanyId().equals(codeParam[1])) {
                equInfo = new EquInfo();
                equInfo.setEquXinghao("上门取件设备");
            } else {
                equInfo = equInfoService.get(codeParam[1]);
                if (null == equInfo) {
                    return R.fail("没有设备信息，设备ID:【" + codeParam[1] + "】");
                }
            }
            if (null == userInfo) {
                return R.fail("未查询到用户信息");
            }
            ajax.put("recurCode", isReCode);
            ajax.put("userInfo", userInfo);
            ajax.put("equInfo", equInfo);

        } catch (Exception e) {
            return R.fail("系统异常-", e.getMessage());
        }
        return R.data(ajax);
    }


    /**
     * 获取包裹信息 通过手机号码
     *
     * @return 废弃
     */
    @ApiOperation(value = "分拣时根据码用户手机获取用户信息和设备信息")
    @GetMapping("/getPackageInfoByPhone")
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "电话号码", required = true)})
    public R getPackageInfoByPhone(@RequestParam String phone) throws Exception {
        AjaxResult ajax = AjaxResult.success();

        return R.data(ajax);
    }


    /**
     * 分拣端-获取垃圾分类信息
     *
     * @return 结果
     */
    @ApiOperation(value = "分拣端-获取垃圾分类信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "level", value = "级别", required = true), @ApiImplicitParam(name =
            "id", value = "上级ID", required = true), @ApiImplicitParam(name = "companyId", value = "companyId",
            required = true)})
    @GetMapping("/list/{level}/{id}/{companyId}")
    public R getRubbishType(@PathVariable("level") @NotEmpty int level, @PathVariable("id") String id, @PathVariable(
            "companyId") String companyId) {
        if (level == 0) {
            level = 2;
        }
        RubbishType sysRubbishType = new RubbishType();
        sysRubbishType.setCompanyId(companyId);
        List<RubbishType> depts = rubbishTypeService.listDataByLevel(sysRubbishType, level, id);
        return R.data(depts);
    }

    /**
     * 分拣端-获取分拣端统计数据
     *
     * @return 结果
     */
//    @ApiOperation(value = "分拣端-获取分拣端统计数据")
//    @GetMapping("/getClintStaticData")
//    public R getClintStaticData() {
//        return R.data(orderService.getClintStaticData(SecurityUtils.getLoginUser().getUser().getCompanyId(),
//                SecurityUtils.getUserId()));
//    }

    /**
     * 分拣端-获取最后10条数据
     *
     * @param order
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "分拣端-获取最后10条数据")
    @GetMapping("/orderList")
    public R<PageInfo> list(Order order, HttpServletRequest request, HttpServletResponse response) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            order.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        order.setUserId(SecurityUtils.getUserId());
        order.setPage(new PageDomain(request, response));
        return R.data(orderService.findPage(order));
    }



    public static boolean isValidPhoneNumber(String phoneNumber) {
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
        }
        return false;
    }


}
